#include <webx/menu.h>
#include <webx/route.h>

class ShareNote : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(ShareNote, "/confile/${filename}")

int ShareNote::process()
{
	param_string(id);
	param_string(dbid);
	param_string(flag);
	param_string(title);
	param_string(folder);

	webx::CheckAlnumString(id, 0);
	webx::CheckFileName(title, 0);
	webx::CheckFileName(folder, 0);

	if (id.empty() && title.empty())
	{
		clearResponse();
		
		return XG_PARAMERR;
	}

	if (flag == "Q")
	{
		webx::CheckSystemRight(this);
	}
	else
	{
		try
		{
			checkLogin();
		}
		catch(Exception e)
		{
		}
	}

	string user;
	string level;
	string sqlcmd;
	string content;

	if (id.empty())
	{
		if (folder.empty())
		{
			sqlcmd = "SELECT USER,LEVEL,CONTENT,FOLDER,TITLE FROM T_XG_CONF WHERE FOLDER='WEBPAGE' AND TITLE='" + title + "'";
		}
		else
		{
			param_name_string(user);

			if (user.empty() && (user = this->user).empty()) user = "system";

			if (dbid.empty()) dbid = this->dbid;

			sqlcmd = "SELECT USER,LEVEL,CONTENT,FOLDER,TITLE FROM T_XG_CONF WHERE USER='" + user + "' AND FOLDER='" + folder + "' AND TITLE='" + title + "'";
		}
	}
	else
	{
		if (dbid.empty()) dbid = this->dbid;

		sqlcmd = "SELECT USER,LEVEL,CONTENT,FOLDER,TITLE FROM T_XG_CONF WHERE ID='" + id + "'";
	}
	
	sp<DBConnect> dbconn;

	try
	{
		dbconn = webx::GetDBConnect(dbid);
	}
	catch(Exception e)
	{
		clearResponse();
		
		return XG_SYSBUSY;
	}

	sp<QueryResult> rs = dbconn->query(sqlcmd);

	if (!rs)
	{
		clearResponse();
		
		return XG_SYSERR;
	}
	
	sp<RowData> row = rs->next();

	if (flag == "Q")
	{
		if (!row) return simpleResponse(XG_NOTFOUND);

		json["content"] = row->getString(2);
		json["folder"] = row->getString(3);
		json["title"] = row->getString(4);
		json["code"] = XG_OK;
		out << json;
	}
	else
	{
		if (!row)
		{
			clearResponse();
		
			return XG_OK;
		}

		user = row->getString(0);
		level = row->getString(1);
		content = row->getString(2);

		if (user == this->user || level[0] > '2')
		{
			out << content;
		}
	}

	return XG_OK;
}